/**
*   Session test (servlet)
*   4/6/2012
*/

package org.buptjunjun.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class ShowSession extends HttpServlet
{
    public void doGet(HttpServletRequest request,
                  	 HttpServletResponse response) 
					 throws IOException ,ServletException
	{
		response.setContentType("text/html");	
		PrintWriter out = response.getWriter();	
	    Integer accessAccount = new Integer(0);
		
		//if session if not exsist ,create one;
		HttpSession session = request.getSession(true);
		String heading = "";
		if(session.isNew())
		{
		    heading = "welcome NewComer";
		}
		else
		{
		    heading = "welcome Back";
			Integer oldAccessCount = (Integer)session.getValue("accessCount");
			if(oldAccessCount != null)
			{
			    accessAccount = oldAccessCount+1;
			}
		}
		
		session.putValue("accessCount",accessAccount);
		out.println("<HTML><BODY>");
		out.println("infomation of your session:<BR>");
		out.println("ID :" + session.getId() + "<BR>");
		out.println("Creation Time :" + session.getCreationTime() + "<BR>");
		out.println("Time of last access :" + new Date(session.getLastAccessedTime())+ "<BR>");
		out.println("Number of last access :" + accessAccount+ "<BR>");
		
		out.println("</BODY></HTML>");
	
	}

    public void doPost(HttpServletRequest request,
	              HttpServletResponse response)
				  throws IOException, ServletException
	{
	    doGet(request,response);
	}
	
	/**
	*   get the value of certain cookie
	*/
	public String getCookieValue(Cookie[] cookies, 
	                             String cookieName,
								 String defauleValue)
	{
	    if (cookies == null || cookies.length == 0 || cookieName == null)
		   return defauleValue;
		for (int i= 0; i < cookies.length; i++)
		{
		    Cookie cookie = cookies[i];
		    if (cookieName.equals(cookie.getName()))
			{
			    return cookie.getValue();
			}
		}
		
		return defauleValue;
	}
}
